<?php
namespace src;
use classlib\acl;
use classlib\input;
use src\logic\Cadmin;
use classlib\core as C;
use classlib\core\controller;
class Corg extends controller {
	public function main() {
		$view   = C\view::inst('extjs');
		$userid = Cadmin::chkaccess($view);
		$view->assign_by_ref('title', Cadmin::$name);
		$view->display('core/org.ext.js');
	}
	
	public function dotree() {
		$view = C\view::inst('json');
		Cadmin::chkaccess($view);
		$field= '*,name as text';
		$sort = array('pid'=>\classlib\orm::ASC);
		$list = C\model::load('main.sys.organize')
			->get_list(0, -1, null, $field, $sort);
		$loop = 0;
		$tree = array();
		$orm  = C\model::load('main.sys.user');
		while (!empty($list)) {
			foreach ($list as $key=>$item) {
				$item['stime'] = date('Y-m-d', $item['stime']);
				if ($item['chargeuid'] > 0 && !isset($item['caccount']) && !isset($item['cnickname'])) {
					$user = $orm->get_one($item['chargeuid']);
					$item['caccount']  = $user['account'];
					$item['cnickname'] = $user['nickname'];
				}
				if ($item['prechargeuid'] > 0 && !isset($item['paccount']) && !isset($item['pnickname'])) {
					$user = $orm->get_one($item['prechargeuid']);
					$item['paccount']  = $user['account'];
					$item['pnickname'] = $user['nickname'];
				}
				if (Cadmin::mk_tree($item, $tree)) {
					unset($list[$key]);
				}
			}
			if ($loop++ > 9) {
				break;
			}
		}
		ob_end_clean();
		$tree = json_encode($tree); 
		echo $tree;
	}
	
	/**
	 * @desc    编辑组织结构信息
	 * @doc     编辑组织结构
	 * @access  需要授权
	 */
	public function dosave() {
		$view   = C\view::inst('json');
		Cadmin::chkaccess($view);
		$data   = array();
		$lang   = C\lang::inst('adm');
		$filter = new \classlib\validator\auditor();
		$filter->lang($lang);
		$id     = (int)input::get_post('id');
		try {
			$data['name']  = $filter->reset('name')->required()->minlen(1)->maxlen(64)->run();
			$data['code']  = $filter->reset('code')->required()->alphanum()->lbetween(1, 8)->run();
			$data['desc']  = $filter->reset('desc')->required()->maxlen(255)->run();
			$data['chargeuid']    = $filter->reset('chargeuid')->required()->numeric()->min(0)->run();
			$data['prechargeuid'] = $filter->reset('prechargeuid')->required()->numeric()->min(0)->run();
			
		} catch (\classlib\validator\AuditorException $e) {
			$view->assign_error($e->getField(), $e->getMessage());
		} catch (\Exception $e) {
			$view->assign_error($e->getCode(), $e->getMessage());
		}
		$data['pid']   = intval(input::post('pid'));
		$data['stime'] = C\config::$nowtime;
		if (input::post('stime')) {
			$data['stime'] = strtotime(input::post('stime'));
		}
		$where = array('code'=>$data['code']);
		$oid   = C\model::load('main.sys.organize')->isexist($where);
		if ($oid  && $oid != $id) {
			$view->assign_error('code', $lang->get('common', '40014'));
		}
		if($id > 0) {
			C\model::load('main.sys.organize')->save($id, $data);
		} else {
			C\model::load('main.sys.organize')->new_one($data);
		}
		$view->display();
	}
}